using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.Reflection;
using System.Threading;
using DevExpress.XtraNavBar;
using DevExpress.XtraBars.Docking;
using THSLib;
using THSERP.BusinessEntities;

namespace THSERP.BaseProvider
{
    public class THSERPScreen:THSScreen
    {
        #region Constants
        public const String cstFieldGroupNonCreatable = "NonCreatable";
        public const String cstFieldGroupNonEditable = "NonEditable";
        public const String cstFieldGroupAction = "Action";
        public const String cstFieldGroupNonAction = "NonAction";

        public const String cstDataSourcePropertyName = "THSDataSource";
        public const String cstDataMemberPropertyName = "THSDataMember";
        #endregion

        private bool IsSearch = false;
        private int _screenID;
        private STScreensInfo _screenInfo;         
        public THSERPScreen():base()
        {            
        }

        public int ScreenID
        {
            get
            {
                return _screenID;
            }
        }

        public STScreensInfo ScreenInfo
        {
            get
            {
                return _screenInfo;
            }
            set
            {
                _screenInfo = value;
            }
        }

        #region Functions to Init Screen

        public override THSScreen Recreate()
        {                        
            THSERPScreen scr = THSERPScreenFactory.GetScreen(this.ScreenNumber, this.Module.Name);
            scr.Name = this.Name;
            scr.ScreenNumber = this.ScreenNumber;
            scr.Module = this.Module;           
            scr.InitializeScreen(_screenInfo);            
            return scr;
        }

        public void InitializeScreen(STScreensInfo objSTScreensInfo)
        {
            this.SuspendLayout();

            _screenInfo = objSTScreensInfo;
            if (_screenInfo != null)
            {
                //hieu.nguyne fix 02/07/2011
                //hieu.nguyne fix 02/07/2011
                this.WindowState = FormWindowState.Maximized;
                this.AutoSize = true;
                this.AutoScaleMode = AutoScaleMode.Dpi;
                this.AutoScroll = true;
                this.AutoSizeMode = AutoSizeMode.GrowOnly;
                this.AdjustFormScrollbars(true);
                //this.AllowFormSkin = true;
                //this.AutoScaleDimensions = this.Size;
                this.VScroll = true;
                this.HScroll = true;
                //
                //No need to active screen _HieuNH_09/05/2010
               //  this.Activated += new EventHandler(Screen_Activated);                
                this.MouseUp += new MouseEventHandler(Screen_MouseUp);
                //InitScreenLookAndFeel();
                //this.BackColor = Color.FromArgb(_screenInfo.STScreenBackColor);                                
                this.ForeColor = Color.FromArgb(_screenInfo.STScreenForeColor);
                this.Font = new Font(_screenInfo.STScreenFontName, (float)_screenInfo.STScreenFontSize, (FontStyle)Enum.Parse(typeof(FontStyle), _screenInfo.STScreenFontStyle));
                this.ScreenNumber = _screenInfo.STScreenNumber;
                if (this.IsDataSubScreen())
                {
                    this.FormClosing += new FormClosingEventHandler(Screen_Closing);
                }
                this.Tag = _screenInfo.STScreenTag;
                if (_screenInfo.STScreenTag == BaseModule.cstDataSubScreen)
                {
                    this.Location = new Point(_screenInfo.STScreenLocationX, _screenInfo.STScreenLocationY);
                    this.Size = new Size(_screenInfo.STScreenSizeWidth, _screenInfo.STScreenSizeHeight);
                }

                this.Text = _screenInfo.STScreenText;

                _screenID = _screenInfo.STScreenID;
                InitializeControls(this.Controls);
                //Add controls to parent screen_HieuNH_09/05/2010
                AddControlsToParentScreen();
                this.ResumeLayout(false);
                this.PerformLayout();
                
            }
        }

        private void InitScreenLookAndFeel()
        {
            ADUsersInfo objADUsersInfo = (ADUsersInfo)new ADUsersController().GetObjectByName(THSApp.CurrentUser);
            if (!String.IsNullOrEmpty(objADUsersInfo.ADUserStyle))
            {
                if (objADUsersInfo.ADUserStyle == "XP")
                {
                    this.LookAndFeel.SetStyle((DevExpress.LookAndFeel.LookAndFeelStyle)Enum.Parse(typeof(DevExpress.LookAndFeel.LookAndFeelStyle), "Office2003"), true, true, objADUsersInfo.ADUserStyleSkin);
                }
                else
                {
                    this.LookAndFeel.SetStyle((DevExpress.LookAndFeel.LookAndFeelStyle)Enum.Parse(typeof(DevExpress.LookAndFeel.LookAndFeelStyle), objADUsersInfo.ADUserStyle), false, false, objADUsersInfo.ADUserStyleSkin);
                }
                    if (objADUsersInfo.ADUserStyle.Equals("Skin"))
                    this.LookAndFeel.SetSkinStyle(objADUsersInfo.ADUserStyleSkin);
            }
            else
            {
                this.LookAndFeel.SetStyle(DevExpress.LookAndFeel.LookAndFeelStyle.Office2003, false, false, objADUsersInfo.ADUserStyleSkin);
            }
        }

        public override void InitializeScreen()
        {
            _screenInfo = new STScreensController().GetScreenByModuleNameAndUserGroupNameAndScreenName(this.Module.Name, THSApp.CurrentUserGroupInfo.ADUserGroupName, this.Name);

            if (_screenInfo != null)
            {
                //No need to active screen _HieuNH_09/05/2010
                // this.Activated += new EventHandler(Screen_Activated);
                this.BackColor = Color.FromArgb(_screenInfo.STScreenBackColor);
                this.ForeColor = Color.FromArgb(_screenInfo.STScreenForeColor);
                this.Font = new Font(_screenInfo.STScreenFontName, (float)_screenInfo.STScreenFontSize, (FontStyle)Enum.Parse(typeof(FontStyle), _screenInfo.STScreenFontStyle));
                this.ScreenNumber = _screenInfo.STScreenNumber;
                if (this.IsDataSubScreen())
                {
                    this.FormClosing += new FormClosingEventHandler(Screen_Closing);
                    this.SizeGripStyle = SizeGripStyle.Hide;
                    this.MinimizeBox = false;
                    this.MaximizeBox = false;
                    this.StartPosition = FormStartPosition.Manual;
                }
                this.Tag = _screenInfo.STScreenTag;
                if (_screenInfo.STScreenTag == BaseModule.cstDataSubScreen)
                {
                    this.Location = new Point(_screenInfo.STScreenLocationX, _screenInfo.STScreenLocationY);
                    this.Size = new Size(_screenInfo.STScreenSizeWidth, _screenInfo.STScreenSizeHeight);
                }
                this.Text = _screenInfo.STScreenText;
                _screenID = _screenInfo.STScreenID;
                InitializeControls(this.Controls);
                //Add controls to parent screen
                AddControlsToParentScreen();
                RegisterContextMenuItemsEvent();
                this.ContextMenuStrip = fld_ctmAction;
            }
        }

        public void InitializeControls(Control.ControlCollection controls)
        {
            try
            {
               
                for (int i = 0; i < controls.Count; i++)
                {
                    Control ctrl = controls[i];

                    ctrl = InitializeControl(ctrl);

                    
                    String strPrivilege = THSDbUtil.GetPropertyStringValue(ctrl, "THSPrivilege");
                    if (!String.IsNullOrEmpty(strPrivilege))
                    {
                        String[] lstPrivilege = strPrivilege.Split(new char[] { ';' });
                        foreach (String privilege in lstPrivilege)
                        {
                            if (((BaseModuleERP)Module).HasPrivilege(privilege))
                                ctrl.Visible = true;
                            else
                                ctrl.Visible = false;
                        }
                    }

                    //Init field format
                    InitializeFieldFormat(ctrl);

                    int iFieldFormatGroupID = 0;

                    STModulesController objModulesController = new STModulesController();
                    STModulesInfo objModulesInfo = (STModulesInfo)objModulesController.GetObjectByName(this.Module.Name);
                    STFieldsInfo objSTFieldsInfo = new STFieldsController().GetFieldBySTModuleIDAndSTUserGroupIDAndSTFieldName(
                                                                        objModulesInfo.STModuleID, THSApp.CurrentUserGroupInfo.ADUserGroupID,
                                                                        ctrl.Name);
                    String strDataSource = THSDbUtil.GetPropertyStringValue(ctrl, cstDataSourcePropertyName);
                    String strDataMember = THSDbUtil.GetPropertyStringValue(ctrl, cstDataMemberPropertyName);
                    String strFieldGroup = THSDbUtil.GetPropertyStringValue(ctrl, "THSFieldGroup");

                    STFieldFormatGroupsInfo objFieldFormatGroupsInfo = (STFieldFormatGroupsInfo)new STFieldFormatGroupsController().GetFieldFormatGroupByModuleNameAndTableNameAndColumnName(this.Module.Name, strDataSource, strDataMember);

                    if (objFieldFormatGroupsInfo != null)
                        iFieldFormatGroupID = objFieldFormatGroupsInfo.STFieldFormatGroupID;
                    ctrl.AccessibleName = String.Format("{0};{1}", strDataSource, strDataMember);
                    if (objSTFieldsInfo != null)
                        ctrl.AccessibleDescription = String.Format("{0};{1};{2}", objSTFieldsInfo.STFieldID, strFieldGroup, iFieldFormatGroupID);

                    //Add field to module's control collection 
                    if (!Module.Contains(ctrl.Name))
                        this.Module.Controls.Add(ctrl.Name, ctrl);
                    else
                        this.Module.Controls[ctrl.Name] = ctrl;

                    
                    if (!String.IsNullOrEmpty(strFieldGroup))
                    {
                        String[] groups = strFieldGroup.Split(new char[] { ';' });
                        for (int j = 0; j < groups.Length; j++)
                        {
                            String group = groups[j].Trim();
                            if (!String.IsNullOrEmpty(group))
                            {
                                BaseModuleERP module = (BaseModuleERP)Module;
                                if (!module.FieldGroupControls.ContainsKey(group))
                                    module.FieldGroupControls.Add(group, new THSLib.ControlCollection());
                                if (!module.FieldGroupControls[group].Contains(ctrl.Name))
                                    module.FieldGroupControls[group].Add(ctrl.Name, ctrl);
                                else
                                    module.FieldGroupControls[group][ctrl.Name] = ctrl;
                                switch (group)
                                {
                                    case THSERPScreen.cstFieldGroupNonCreatable:
                                    case THSERPScreen.cstFieldGroupNonEditable:
                                    case THSERPScreen.cstFieldGroupAction:
                                        ctrl.Enabled = false;
                                        break;
                                    case THSERPScreen.cstFieldGroupNonAction:
                                        ctrl.Enabled = true;
                                        break;
                                }
                            }
                        }
                    }

                    if (ctrl.Controls.Count > 0)
                        InitializeControls(ctrl.Controls);
                }
            }
            catch (Exception)
            {

            }
        }

        /// <summary>
        /// Initialize specific control
        /// </summary>
        
        public Control InitializeControl(Control ctr)
        {
            #region THSTextBox
            if (ctr.GetType() == typeof(THSTextBox))
            {
                THSTextBox txt = (THSTextBox)ctr;
                txt.Screen = this;
                txt.InitializeControl();
                return txt;
            }
            #endregion

            #region THSMemoEdit
            else if (ctr.GetType() == typeof(THSMemoEdit))
            {
                THSMemoEdit med = (THSMemoEdit)ctr;
                med.Screen = this;
                med.InitializeControl();
                return med;
            }
            #endregion

            #region THSButton
            else if (ctr.GetType() == typeof(THSButton))
            {
                THSButton btn = (THSButton)ctr;
                btn.Screen = this;
                btn.InitializeControl();
                return btn;
            }
            #endregion

            #region THSLabel
            else if (ctr.GetType() == typeof(THSLabel))
            {
                THSLabel lbl = (THSLabel)ctr;
                lbl.Screen = this;
                lbl.InitializeControl();
                return lbl;
            }
            #endregion

            #region THSCheckEdit
            else if(ctr.GetType() == typeof(THSCheckEdit))
            {
                THSCheckEdit chk = (THSCheckEdit)ctr;
                chk.Screen = this;
                chk.InitializeControl();
                return chk;
            }
            #endregion

            #region THSComboBox
            else if (ctr.GetType() == typeof(THSComboBox))
            {
                THSComboBox cmb = (THSComboBox)ctr;
                cmb.Screen = this;
                cmb.InitializeControl();
                return cmb;
            }
            #endregion

            #region THSDateEdit
            else if (ctr.GetType() == typeof(THSDateEdit))
            {
                THSDateEdit dte = (THSDateEdit)ctr;
                dte.Screen = this;
                dte.InitializeControl();
                return dte;
            }
            #endregion

            #region THSTimeEdit
            else if (ctr.GetType() == typeof(THSTimeEdit))
            {
                THSTimeEdit ted = (THSTimeEdit)ctr;
                ted.Screen = this;
                ted.InitializeControl();
                return ted;
            }
            #endregion

            #region THSPictureEdit
            else if (ctr.GetType() == typeof(THSPictureEdit))
            {
                THSPictureEdit pte = (THSPictureEdit)ctr;
                pte.Screen = this;
                pte.InitializeControl();
                return pte;
            }
            #endregion

            #region THSLookupEdit
            else if (ctr.GetType() == typeof(THSLookupEdit))
            {
                
                THSLookupEdit lookupEdit = (THSLookupEdit)ctr;
                lookupEdit.Screen = this;
                lookupEdit.InitializeControl();
                return lookupEdit;
            }
            #endregion
            #region--GridlookupEdit--
            //else if (ctr.GetType() == typeof(THSGridLookupEdit))
            //{
            //    THSGridLookupEdit gridLookupEdit = (THSGridLookupEdit)ctr;
            //    gridLookupEdit.Screen = this;
            //    gridLookupEdit.InitializeControl
            //}
            #endregion
            #region THSLine
            else if (ctr.GetType() == typeof(THSLine))
            {
                THSLine line = (THSLine)ctr;
                line.InitializeControl();
                return line;
            }
            #endregion

            #region THSGridControl
            else if (ctr.GetType() == typeof(THSGridControl) || ctr.GetType().BaseType == typeof(THSGridControl))
            {

                THSGridControl THSGridControl = (THSGridControl)ctr;
                THSGridControl.Screen = this;

                THSGridControl.InitializeControl();
                return THSGridControl;
            }
            #endregion

            #region THSSearchResultsGridControl
            else if (ctr.GetType() == typeof(THSSearchResultsGridControl))
            {
                THSSearchResultsGridControl THSSearchGridControl = (THSSearchResultsGridControl)ctr;
                THSSearchGridControl.Screen = this;
                THSSearchGridControl.InitializeControl();
                return THSSearchGridControl;
            }

            #endregion

            #region THSGroupControl
            else if (ctr.GetType() == typeof(THSGroupControl))
            {
                THSGroupControl grc = (THSGroupControl)ctr;
                grc.Screen = this;
                grc.InitializeControl();
                return grc;
            }
            #endregion

            #region THSTreeList

            else if (ctr.GetType() == typeof(THSTreeListControl) || ctr.GetType().BaseType == typeof(THSTreeListControl))
            {
                THSTreeListControl treeList = (THSTreeListControl)ctr;
                treeList.Screen = this;
                treeList.InitializeControl();
                return treeList;
            }
            #endregion

            #region THSPivotGridControl

            else if (ctr.GetType() == typeof(THSPivotGridControl))
            {
                THSPivotGridControl pvGrid = (THSPivotGridControl)ctr;
                pvGrid.Screen = this;
                pvGrid.InitializeControl();
                return pvGrid;
            }
            #endregion

            #region THSChartControl

            else if (ctr.GetType() == typeof(THSChartControl))
            {
                THSChartControl chrt = (THSChartControl)ctr;
                chrt.Screen = this;
                chrt.InitializeControl();
                return chrt;
            }
            #endregion

            else
                return ctr;
        }
        
        
        public void InitializeControlEvent(STFieldsInfo objSTFieldsInfo,Control ctrl)
        {
            try
            {
                STFieldEventsController objSTFieldEventsController = new STFieldEventsController();                
                DataSet dsFieldEvent = objSTFieldEventsController.GetFieldEventByFieldID(objSTFieldsInfo.STFieldID);
                if (dsFieldEvent.Tables.Count > 0)
                {
                    foreach (DataRow rowFieldEvent in dsFieldEvent.Tables[0].Rows)
                    {
                        STFieldEventsInfo objSTFieldEventsInfo = (STFieldEventsInfo)objSTFieldEventsController.GetObjectFromDataRow(rowFieldEvent);

                        EventInfo ctrlEvent = ctrl.GetType().GetEvent(objSTFieldEventsInfo.STFieldEventName);
                        if (!ctrlEvent.Name.Equals("KeyUp"))
                        {
                            String strMethodName = objSTFieldEventsInfo.STFieldEventDelegateFunctionName;

                            MethodInfo ctrlMethod = this.Module.GetMethodInfoByMethodFullNameAndMethodClass(objSTFieldEventsInfo.STFieldEventDelegateFunctionName, objSTFieldEventsInfo.STFieldEventDelegateFunctionFullName, objSTFieldEventsInfo.STFieldEventDelegateFunctionClass);

                            Delegate ctrlEventDelegate = null;

                            ctrlEventDelegate = Delegate.CreateDelegate(ctrlEvent.EventHandlerType, this.Module, ctrlMethod);

                            ctrlEvent.AddEventHandler(ctrl, ctrlEventDelegate);

                        }
                    }
                }
                dsFieldEvent.Dispose();
            }
            catch (Exception e)
            {
                MessageBox.Show(this.GetType().Name + ".InitializeControlEvent:" + e.Message);
            }
        }

        public void BindingDataControl(Control ctrl)
        {
            try
            {
               
                String strDataSource = THSDbUtil.GetPropertyStringValue(ctrl, cstDataSourcePropertyName);
                String strDataMember = THSDbUtil.GetPropertyStringValue(ctrl, cstDataMemberPropertyName);
                String strPropertyName = THSDbUtil.GetPropertyStringValue(ctrl, "THSPropertyName");
                if (ctrl.Tag.Equals(DataControl))
                {
                    String strMainModuleTable = THSUtil.GetTableNameFromBusinessObject(((BaseModuleERP)Module).CurrentModuleEntity.MainObject);
                    if (strDataSource.Equals(strMainModuleTable))
                    {
                        if (((BaseModuleERP)Module).CurrentModuleEntity.MainObject != null)
                        {
                            ctrl.DataBindings.Add(
                                            new Binding( strPropertyName,
                                            ((BaseModuleERP)this.Module).CurrentModuleEntity.MainObjectBindingSource,
                                            strDataMember,
                                            true,
                                            DataSourceUpdateMode.OnPropertyChanged));
                        }
                    }
                    else
                        if (((BaseModuleERP)Module).CurrentModuleEntity.ModuleObjects[strDataSource] != null)
                        {
                            ctrl.DataBindings.Add(
                                            new Binding(strPropertyName,
                                            ((BaseModuleERP)this.Module).CurrentModuleEntity.ModuleObjectsBindingSource[strDataSource],
                                            strDataMember,
                                            true,
                                            DataSourceUpdateMode.OnPropertyChanged));
                        }
                }
            }
            catch (Exception)
            {
               
            }
        }
        #endregion       

        
        public virtual void InitializeFieldFormat(Control ctrl)
        {
           
            String strTableName = THSDbUtil.GetPropertyStringValue(ctrl, cstDataSourcePropertyName);
            String strColumnName = THSDbUtil.GetPropertyStringValue(ctrl, cstDataMemberPropertyName);

            if (!String.IsNullOrEmpty(strTableName) && !String.IsNullOrEmpty(strColumnName))
            {
                STFieldFormatGroupsController objFieldFormatGroupsController = new STFieldFormatGroupsController();
                STFieldFormatGroupsInfo objFieldFormatGroupsInfo = (STFieldFormatGroupsInfo)objFieldFormatGroupsController.GetFieldFormatGroupByModuleNameAndTableNameAndColumnName(this.Module.Name, strTableName, strColumnName);
                if (objFieldFormatGroupsInfo != null)
                {
                    if (objFieldFormatGroupsInfo.STFieldFormatGroupBackColor > 0)
                        ctrl.BackColor = Color.FromArgb(objFieldFormatGroupsInfo.STFieldFormatGroupBackColor);
                    if (objFieldFormatGroupsInfo.STFieldFormatGroupForeColor > 0)
                        ctrl.ForeColor = Color.FromArgb(objFieldFormatGroupsInfo.STFieldFormatGroupForeColor);

                    String strDefaultFontName = "Tahoma";
                    float fDefaultFontSize = 8.25F;
                    if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupFontName))
                        strDefaultFontName = objFieldFormatGroupsInfo.STFieldFormatGroupFontName;
                    if (objFieldFormatGroupsInfo.STFieldFormatGroupFontSize > 0)
                        fDefaultFontSize = objFieldFormatGroupsInfo.STFieldFormatGroupFontSize;
                    ctrl.Font = new Font(strDefaultFontName, fDefaultFontSize);

                    if (THSUtil.IsEditControl(ctrl))
                    {
                        DevExpress.XtraEditors.TextEdit txt = (DevExpress.XtraEditors.TextEdit)ctrl;
                        if (objFieldFormatGroupsInfo.STFieldFormatGroupDecimalRound > 0)
                        {
                            txt.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
                            txt.Properties.Mask.EditMask = String.Format("n{0}", objFieldFormatGroupsInfo.STFieldFormatGroupDecimalRound);
                            txt.Properties.Mask.UseMaskAsDisplayFormat = true;
                        }
                        else
                        {
                            if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupMaskType))
                            {
                                txt.Properties.Mask.MaskType = THSUtil.GetMaskTypeFromText(objFieldFormatGroupsInfo.STFieldFormatGroupMaskType);
                                txt.Properties.Mask.EditMask = objFieldFormatGroupsInfo.STFieldFormatGroupMaskEdit;
                                txt.Properties.Mask.UseMaskAsDisplayFormat = true;
                            }
                            if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupFormatType))
                            {
                                txt.Properties.DisplayFormat.FormatType = THSUtil.GetFormatTypeFromText(objFieldFormatGroupsInfo.STFieldFormatGroupFormatType);
                                txt.Properties.DisplayFormat.FormatString = objFieldFormatGroupsInfo.STFieldFormatGroupFormatString;
                            }
                        }
                    }
                }
            }
        }

        #region Initialize Toolbar Functions
        private void InitializeToolbar()
        {
            STFieldsController objSTFieldsController = new STFieldsController();
            this.screenToolbar.Images = THSApp.ToolbarImageList;

            DataSet dsToolbarButtons = objSTFieldsController.GetFieldByScreenIDAndUserGroupIDAndFieldType(ScreenID, THSApp.CurrentUserGroupInfo.ADUserGroupID, "THSToolbarButton");
            if (dsToolbarButtons.Tables.Count > 0)
            {
                if (dsToolbarButtons.Tables[0].Rows.Count > 0)
                {
                    DevExpress.XtraBars.Bar toolbarGroup = new DevExpress.XtraBars.Bar(this.screenToolbar);                    
                    toolbarGroup.BarName = "Screen Toolbar";                    
                    toolbarGroup.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;                    
                    screenToolbar.Bars.Add(toolbarGroup);

                    foreach (DataRow rowToolbarButton in dsToolbarButtons.Tables[0].Rows)
                    {
                        THSLib.STFieldsInfo objSTFieldsInfo = objSTFieldsController.GetFieldByFieldNameAndScreenIDAndUserGroupID(rowToolbarButton["STFieldName"].ToString(), ScreenID, THSApp.CurrentUserGroupInfo.ADUserGroupID);
                       // DevExpress.XtraBars.BarButtonItem toolbarButton = InitializeToolbarButton(objSTFieldsInfo, THSApp.CurrentUserGroupInfo.ADLanguageIDCombo);
                        DevExpress.XtraBars.BarButtonItem toolbarButton = InitializeToolbarButton(objSTFieldsInfo, THSApp.CurrentUserGroupInfo.ADLanguageIDCombo);
                        toolbarButton.Id = screenToolbar.GetNewItemId();
                        screenToolbar.Items.Add((DevExpress.XtraBars.BarItem)toolbarButton);
                        screenToolbar.Bars[0].AddItem((DevExpress.XtraBars.BarItem)toolbarButton);
                    }
                }
            }
            dsToolbarButtons.Dispose();
           
        }
      
        private DevExpress.XtraBars.BarButtonItem InitializeToolbarButton(STFieldsInfo objSTFieldsInfo, int iLanguageID)
        {
           
            DevExpress.XtraBars.BarButtonItem toolbarButton = new DevExpress.XtraBars.BarButtonItem();
            toolbarButton.Name = objSTFieldsInfo.STFieldName;
            //  toolbarButton.Font = new Font(objSTFieldsInfo.STFieldFontName, (float)objSTFieldsInfo.STFieldFontSize, (FontStyle)Enum.Parse(typeof(FontStyle), objSTFieldsInfo.STFieldFontStyle));
            //toolbarButton.Use = false;
            toolbarButton.LargeImageIndex = THSApp.ToolbarImageList.Images.IndexOfKey("Save");
            toolbarButton.Caption = objSTFieldsInfo.STFieldText;
            InitializeToolbarButtonEvent(objSTFieldsInfo, toolbarButton);
            return toolbarButton;
        }

        public void InitializeToolbarButtonEvent(STFieldsInfo objSTFieldsInfo, DevExpress.XtraBars.BarButtonItem toolbarButton)
        {
            try
            {
                STFieldEventsController objSTFieldEventsController = new STFieldEventsController();
                DataSet dsToolbarButtonEvent = objSTFieldEventsController.GetFieldEventByFieldID(objSTFieldsInfo.STFieldID);
                if (dsToolbarButtonEvent.Tables.Count > 0)
                {
                    foreach (DataRow rowToolbarButtonEvent in dsToolbarButtonEvent.Tables[0].Rows)
                    {
                        STFieldEventsInfo objSTFieldEventsInfo = (STFieldEventsInfo)new STFieldEventsController().GetObjectFromDataRow(rowToolbarButtonEvent);
                        EventInfo toolbarButtonEvent = toolbarButton.GetType().GetEvent(objSTFieldEventsInfo.STFieldEventName);
                        String strMethodName = objSTFieldEventsInfo.STFieldEventDelegateFunctionName;
                        MethodInfo ctrlMethod = this.Module.GetMethodInfoByMethodFullNameAndMethodClass(objSTFieldEventsInfo.STFieldEventDelegateFunctionName, objSTFieldEventsInfo.STFieldEventDelegateFunctionFullName, objSTFieldEventsInfo.STFieldEventDelegateFunctionClass);

                        Delegate ctrlEventDelegate = Delegate.CreateDelegate(toolbarButtonEvent.EventHandlerType, this.Module, ctrlMethod);
                        toolbarButtonEvent.AddEventHandler(toolbarButton, ctrlEventDelegate);

                    }
                }
                dsToolbarButtonEvent.Dispose();
            }
            catch (Exception e)
            {
                MessageBox.Show(this.GetType().Name + ".InitializeControlEvent:" + e.Message);
            }
        }
        #endregion

        #region Initialize TextBox Function
        public DevExpress.XtraEditors.TextEdit InitializeTextBox(STFieldsInfo Field,int iLanguageID)
        {
            try
            {
                DevExpress.XtraEditors.TextEdit txt = new DevExpress.XtraEditors.TextEdit();
                txt.Name = Field.STFieldName;
                txt.BackColor = Color.FromArgb(Field.STFieldBackColor);
                txt.ForeColor = Color.FromArgb(Field.STFieldForeColor);
                txt.Font = new Font(Field.STFieldFontName, (float)Field.STFieldFontSize, (FontStyle)Enum.Parse(typeof(FontStyle), Field.STFieldFontStyle));
                txt.Location = new Point(Field.STFieldLocationX, Field.STFieldLocationY);
                txt.Size = new Size(Field.STFieldSizeWidth, Field.STFieldSizeHeight);
                txt.Enabled = Field.STFieldEnabled;
                txt.TabIndex = Field.STFieldTabIndex;
                txt.Tag = Field.STFieldTag;
                
               
                txt.Properties.Mask.MaskType = (DevExpress.XtraEditors.Mask.MaskType)Enum.Parse(typeof(DevExpress.XtraEditors.Mask.MaskType), Field.STFieldMaskType);
                txt.Properties.Mask.EditMask = Field.STFieldEditMask;
                txt.Properties.Mask.UseMaskAsDisplayFormat = true;

                txt.Properties.ReadOnly = Field.STFieldReadOnly;
                txt.RightToLeft = (RightToLeft)Enum.Parse(typeof(RightToLeft), Field.STFieldRightToLeft);
                txt.Properties.BorderStyle = (DevExpress.XtraEditors.Controls.BorderStyles)Enum.Parse(typeof(DevExpress.XtraEditors.Controls.BorderStyles), Field.STFieldBorderStyle);

                //Init Character Casing
                if (!String.IsNullOrEmpty(Field.STFieldCharacterCase))
                    txt.Properties.CharacterCasing = (CharacterCasing)Enum.Parse(typeof(CharacterCasing), Field.STFieldCharacterCase);
                if (!String.IsNullOrEmpty(Field.STFieldDataSource) && !String.IsNullOrEmpty(Field.STFieldDataMember))
                    BindingDataControl(txt);
                
                
                txt.Click += new EventHandler(((BaseModuleERP)Module).Control_Click);

                txt.KeyUp += new KeyEventHandler(((BaseModuleERP)Module).Control_KeyUp);                
                
                if (THSDbUtil.IsForeignKey(Field.STFieldDataSource, Field.STFieldDataMember)&&Field.STFieldTag.Equals(THSScreen.DataControl))
                {
                    txt.EditValueChanged += new EventHandler(((BaseModuleERP)Module).Control_EditValueChanged);
                }

                //Register Control Leave
                String strMainObjectTableName = THSUtil.GetTableNameFromBusinessObject(((BaseModuleERP)Module).CurrentModuleEntity.MainObject);
                String strMainObjectNameColumn = strMainObjectTableName.Substring(0, strMainObjectTableName.Length - 1) + "Name";
                if(txt.Name.Substring(7).Equals(strMainObjectNameColumn))
                    txt.Leave+=new EventHandler(Control_Leave);

                //Init Default Value if Control is Top Results
                if (Field.STFieldName == THSApp.cstTopResultsSearchControl)
                    txt.Text = THSApp.cstTopResults.ToString();

                InitializeControlEvent(Field, txt);
                return txt;
            }
            catch (Exception)
            {
                return null;
            }
        }
        
        public void InitTextBoxMaskEdit(STFieldsInfo Field, DevExpress.XtraEditors.TextEdit txt)
        {
           
            if (THSDbUtil.IsForeignKey(Field.STFieldDataSource, Field.STFieldDataMember))
            {
                String strLookupTable = THSDbUtil.GetPrimaryTableWhichForeignColumnReferenceTo(Field.STFieldDataSource, Field.STFieldDataMember);
                String strLookupModuleName = THSUtil.GetModuleName(strLookupTable);
                STModulesController objSTModulesController = new STModulesController();
                if (objSTModulesController.IsExistObjectName(strLookupModuleName))
                {
                    GENumberingController objGENumberingController = new GENumberingController();
                    GENumberingInfo objGENumberingInfo = (GENumberingInfo)objGENumberingController.GetObjectByName(strLookupModuleName);
                    if (objGENumberingInfo != null)
                    {
                        txt.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
                        txt.Properties.Mask.EditMask = "d" + objGENumberingInfo.GENumberingLength.ToString();
                        txt.Properties.Mask.UseMaskAsDisplayFormat = true;
                    }
                    else
                    {
                        txt.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
                        txt.Properties.Mask.EditMask = "d6";
                        txt.Properties.Mask.UseMaskAsDisplayFormat = true;
                    }
                }
                else
                {
                    txt.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
                    txt.Properties.Mask.EditMask = "d6";
                    txt.Properties.Mask.UseMaskAsDisplayFormat = true;
                }
            }
            else
            {
                //If Field is FAProductID1,FAProductID2,FAProductID3
                if ((Field.STFieldTag == THSScreen.SearchControl) && (!String.IsNullOrEmpty(Field.STFieldGroup)))
                {
                    String strLookupTable = Field.STFieldGroup;
                    String strLookupModuleName = THSUtil.GetModuleName(strLookupTable);
                    STModulesController objSTModulesController = new STModulesController();
                    if (objSTModulesController.IsExistObjectName(strLookupModuleName))
                    {
                        GENumberingController objGENumberingController = new GENumberingController();
                        GENumberingInfo objGENumberingInfo = (GENumberingInfo)objGENumberingController.GetObjectByName(strLookupModuleName);
                        if (objGENumberingInfo != null)
                        {
                            txt.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
                            txt.Properties.Mask.EditMask = "d" + objGENumberingInfo.GENumberingLength.ToString();
                            txt.Properties.Mask.UseMaskAsDisplayFormat = true;
                        }
                        else
                        {
                            txt.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
                            txt.Properties.Mask.EditMask = "d6";
                            txt.Properties.Mask.UseMaskAsDisplayFormat = true;
                        }
                    }
                    else
                    {
                        txt.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
                        txt.Properties.Mask.EditMask = "d6";
                        txt.Properties.Mask.UseMaskAsDisplayFormat = true;
                    }
                }
                else
                {
                    txt.Properties.Mask.EditMask = Field.STFieldEditMask;
                    txt.Properties.Mask.MaskType = (DevExpress.XtraEditors.Mask.MaskType)Enum.Parse(typeof(DevExpress.XtraEditors.Mask.MaskType), Field.STFieldMaskType);
                    txt.Properties.Mask.UseMaskAsDisplayFormat = true;
                }
            }
        }
     
        #endregion

        #region Initialize MemoEdit function
        public DevExpress.XtraEditors.MemoEdit InitializeMemoEdit(STFieldsInfo Field, int iLanguageID)
        {
            try
            {
                DevExpress.XtraEditors.MemoEdit med = new DevExpress.XtraEditors.MemoEdit();
                med.Name = Field.STFieldName;
                med.BackColor = Color.FromArgb(Field.STFieldBackColor);
                med.ForeColor = Color.FromArgb(Field.STFieldForeColor);
                med.Font = new Font(Field.STFieldFontName, (float)Field.STFieldFontSize, (FontStyle)Enum.Parse(typeof(FontStyle), Field.STFieldFontStyle));
                med.Location = new Point(Field.STFieldLocationX, Field.STFieldLocationY);
                med.Size = new Size(Field.STFieldSizeWidth, Field.STFieldSizeHeight);
                med.Enabled = Field.STFieldEnabled;
                med.TabIndex = Field.STFieldTabIndex;
                med.Tag = Field.STFieldTag;
                med.Properties.ReadOnly = Field.STFieldReadOnly;
                med.Properties.ScrollBars = (ScrollBars)Enum.Parse(typeof(ScrollBars), Field.STFieldScrollBars);
                //med.EnterMoveNextControl = true;
                //Init Character Casing
                if (!String.IsNullOrEmpty(Field.STFieldCharacterCase))
                    med.Properties.CharacterCasing = (CharacterCasing)Enum.Parse(typeof(CharacterCasing), Field.STFieldCharacterCase);
                if (!String.IsNullOrEmpty(Field.STFieldDataSource) && !String.IsNullOrEmpty(Field.STFieldDataMember))
                    BindingDataControl(med);
                med.Click += new EventHandler(((BaseModuleERP)Module).Control_Click);                
                med.Leave += new EventHandler(Control_Leave);
                med.KeyUp += new KeyEventHandler(((BaseModuleERP)Module).Control_KeyUp);
                InitializeControlEvent(Field, med);
                return med;
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        #region Initialize Button function
        public DevExpress.XtraEditors.SimpleButton InitializeButton(STFieldsInfo Field,int iLanguageID)
        {
            try
            {
                DevExpress.XtraEditors.SimpleButton btn = new DevExpress.XtraEditors.SimpleButton();
                btn.Name = Field.STFieldName;
                btn.BackColor = Color.FromArgb(Field.STFieldBackColor);
                btn.ForeColor = Color.FromArgb(Field.STFieldForeColor);
                btn.Font = new Font(Field.STFieldFontName, (float)Field.STFieldFontSize, (FontStyle)Enum.Parse(typeof(FontStyle), Field.STFieldFontStyle));
                btn.Location = new Point(Field.STFieldLocationX, Field.STFieldLocationY);
                btn.Size = new Size(Field.STFieldSizeWidth, Field.STFieldSizeHeight);
                btn.Enabled = Field.STFieldEnabled;
                btn.TabIndex = Field.STFieldTabIndex;
                btn.Tag = Field.STFieldTag;
                btn.Text = Field.STFieldText;
                btn.BackColor = Color.Transparent;
                //btn.Text = Field.STFieldText;
                //btn.TextAlign = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), Field.STFieldTextAlign);
                btn.KeyUp += new KeyEventHandler(((BaseModuleERP)Module).Control_KeyUp);
                InitializeControlEvent(Field, btn);
                return btn;
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        #region Initialize Check Edit function
        public DevExpress.XtraEditors.CheckEdit InitializeCheckEdit(STFieldsInfo Field,int iLanguageID)
        {
            try
            {
                DevExpress.XtraEditors.CheckEdit chk = new DevExpress.XtraEditors.CheckEdit();
                chk.Name = Field.STFieldName;
                chk.BackColor = Color.FromArgb(Field.STFieldBackColor);
                chk.ForeColor = Color.FromArgb(Field.STFieldForeColor);
                chk.Font = new Font(Field.STFieldFontName, (float)Field.STFieldFontSize, (FontStyle)Enum.Parse(typeof(FontStyle), Field.STFieldFontStyle));
                chk.Location = new Point(Field.STFieldLocationX, Field.STFieldLocationY);
                chk.Tag = Field.STFieldTag;
                chk.Size = new Size(Field.STFieldSizeWidth, Field.STFieldSizeHeight);
                chk.Enabled = Field.STFieldEnabled;
                chk.TabIndex = Field.STFieldTabIndex;
                //chk.Text = Field.STFieldText;
                GetCheckEditText(Field,ref chk);
                chk.Properties.CheckStyle = (DevExpress.XtraEditors.Controls.CheckStyles)Enum.Parse(typeof(DevExpress.XtraEditors.Controls.CheckStyles), Field.STFieldCheckedStyle);
                //Binding data if CheckEdit have datasource of datamember
                if (!String.IsNullOrEmpty(Field.STFieldDataSource) && !String.IsNullOrEmpty(Field.STFieldDataMember))
                    BindingDataControl(chk);
                chk.KeyUp += new KeyEventHandler(((BaseModuleERP)Module).Control_KeyUp);
                InitializeControlEvent(Field, chk);
                return chk;
            }
            catch (Exception)
            {
                return null;
            }
        }

        private void GetCheckEditText(STFieldsInfo Field,ref DevExpress.XtraEditors.CheckEdit chk)
        {
            if (!String.IsNullOrEmpty(Field.STFieldDataSource) && !String.IsNullOrEmpty(Field.STFieldDataMember))
            {
                if (Field.STFieldDataSource.Equals(ADConfigValueUtility.ADConfigValueTable))
                {
                    String strValue = ADConfigValueUtility.GetTextFromKey(Field.STFieldDataMember);
                    if (strValue != string.Empty)
                        chk.Text = strValue;
                    else
                        chk.Text = Field.STFieldText;

                }
                else
                    chk.Text = Field.STFieldText;
            }
            else
                chk.Text = Field.STFieldText;
        }
        #endregion

        #region Initialize Label function
        public DevExpress.XtraEditors.LabelControl InitializeLabel(STFieldsInfo Field, int iLanguageID)
        {
            DevExpress.XtraEditors.LabelControl lbl = new DevExpress.XtraEditors.LabelControl();
            lbl.Name = Field.STFieldName;
            //lbl.BackColor = Color.FromArgb(Field.STFieldBackColor);
            lbl.BackColor = Color.Transparent;
            lbl.ForeColor = Color.FromArgb(Field.STFieldForeColor);
            lbl.Font = new Font(Field.STFieldFontName, (float)Field.STFieldFontSize, (FontStyle)Enum.Parse(typeof(FontStyle), Field.STFieldFontStyle));
            lbl.Location = new Point(Field.STFieldLocationX, Field.STFieldLocationY);
            lbl.Size = new Size(Field.STFieldSizeWidth, Field.STFieldSizeHeight);
            lbl.AutoSize = true;
            lbl.Enabled = Field.STFieldEnabled;
            lbl.TabIndex = Field.STFieldTabIndex;
            //lbl.TextAlign = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), Field.STFieldTextAlign);
            GetLabelText(Field, ref lbl);
            InitializeControlEvent(Field, lbl);
            return lbl;
        }

        private void GetLabelText(STFieldsInfo Field,ref DevExpress.XtraEditors.LabelControl lbl)
        {
            if (!String.IsNullOrEmpty(Field.STFieldDataSource) && !String.IsNullOrEmpty(Field.STFieldDataMember))
            {
                if (Field.STFieldDataSource.Equals("ADConfigValues"))
                {
                    String strText = ADConfigValueUtility.GetTextFromKey(Field.STFieldDataMember);
                    
                    if (!String.IsNullOrEmpty(strText))
                        lbl.Text = strText;
                    else
                        lbl.Text = Field.STFieldText;
                }
                else
                {
                    Field.STFieldBindingPropertyName = "Text";
                    lbl.Tag = "DC";
                    if (!String.IsNullOrEmpty(Field.STFieldDataSource) && !String.IsNullOrEmpty(Field.STFieldDataMember))
                        BindingDataControl(lbl);
                }

            }
            else
            {
                lbl.Text = Field.STFieldText;
                //add lable tag ,HieuNH_01/04/2010
                lbl.Tag = Field.STFieldTag;
            }
        }
        #endregion

        #region Initialize ComboBox function
        public DevExpress.XtraEditors.ComboBoxEdit InitializeComboBox(STFieldsInfo Field,int iLanguageID)
        {
            try
            {
                DevExpress.XtraEditors.ComboBoxEdit cmb = new DevExpress.XtraEditors.ComboBoxEdit();
                cmb.Name = Field.STFieldName;
                cmb.BackColor = Color.FromArgb(Field.STFieldBackColor);
                cmb.ForeColor = Color.FromArgb(Field.STFieldForeColor);
                cmb.Font = new Font(Field.STFieldFontName, (float)Field.STFieldFontSize, (FontStyle)Enum.Parse(typeof(FontStyle), Field.STFieldFontStyle));
                cmb.Location = new Point(Field.STFieldLocationX, Field.STFieldLocationY);
                cmb.Size = new Size(Field.STFieldSizeWidth, Field.STFieldSizeHeight);
                cmb.Enabled = Field.STFieldEnabled;
                cmb.Tag = Field.STFieldTag;
                cmb.Properties.TextEditStyle = (DevExpress.XtraEditors.Controls.TextEditStyles)Enum.Parse(typeof(DevExpress.XtraEditors.Controls.TextEditStyles), Field.STFieldTextEditStyle);
                
                cmb.TabIndex = Field.STFieldTabIndex;
                InitObjectDataToComboBox(Field,cmb);
                
                if (!String.IsNullOrEmpty(Field.STFieldDataSource) && !String.IsNullOrEmpty(Field.STFieldDataMember))
                {
                    if (!Field.STFieldDataSource.Equals("ADConfigValues"))
                        BindingDataControl(cmb);
                }

                //Set Edit Value of Combo Box is String.Empty if FieldTag is SC
                if (Field.STFieldTag == SearchControl)
                {
                    cmb.EditValue = String.Empty;
                }

                cmb.Click += new EventHandler(((BaseModuleERP)Module).Control_Click);                
                cmb.KeyUp += new KeyEventHandler(((BaseModuleERP)Module).Control_KeyUp);
                InitializeControlEvent(Field, cmb);
                return cmb;
            }
            catch (Exception)
            {
                MessageBox.Show("#Message# Bug ComboBox !");
                return null;
            }
        }

        private void InitObjectDataToComboBox(STFieldsInfo Field,DevExpress.XtraEditors.ComboBoxEdit cmb)
        {                                       
            //ComboBox is MatchCode
            if (Field.STFieldDataMember.Contains("MatchCode"))
            {
                InitMatchCodeValueToComboBox(Field.STFieldDataMember,Field.STFieldTag , cmb);
            }
            else if ((Field.STFieldDataSource.Contains("ADConfigValues")) && !String.IsNullOrEmpty(Field.STFieldDataMember))
            {
                InitComboBoxFromADConfigValues(Field, cmb);
            }
        }

        private void InitItemCollectionToComboBox(STFieldsInfo objSTFieldsInfo, ComboBox cmb)
        {
            String strItemCollectionString = objSTFieldsInfo.STFieldItemCollection;
            DataTable table = InitDataTableForCombBoxHaveItemCollection();
            while (strItemCollectionString.Contains(";"))
            {
                String strItemText = strItemCollectionString.Substring(0, strItemCollectionString.IndexOf(";"));
                String strItemValue = strItemText.Substring(0, 2);
                table.Rows.Add(new object[2] { strItemText, strItemValue });
                strItemCollectionString = strItemCollectionString.Substring(strItemCollectionString.IndexOf(";") + 1);
            }
            if (!String.IsNullOrEmpty(strItemCollectionString))
            {
                table.Rows.Add(new object[2] { strItemCollectionString, strItemCollectionString.Substring(0, 2) });
            }
            cmb.DataSource = table;
            cmb.DisplayMember = "Text";
            cmb.ValueMember = "Value";
        }

        private DataTable InitDataTableForCombBoxHaveItemCollection()
        {
            DataTable table = new DataTable();
            DataColumn columnText = new DataColumn("Text", typeof(string));
            table.Columns.Add(columnText);
            DataColumn columnValue = new DataColumn("Value", typeof(string));
            table.Columns.Add(columnValue);
            return table;
        }
        

        private void InitMatchCodeValueToComboBox(String strMatchCodeColumnName, String strFieldTag, DevExpress.XtraEditors.ComboBoxEdit cmbMatchCode)
        {
            cmbMatchCode.Properties.Items.Clear();
            ADMatchCodesController objADMatchCodesController = new ADMatchCodesController();
            DataSet dsMatchCodeValue = objADMatchCodesController.GetADMatchCodesByADMatchCodeColumnName(strMatchCodeColumnName);
            if (dsMatchCodeValue.Tables.Count > 0)
            {
                if (dsMatchCodeValue.Tables[0].Rows.Count > 0)
                {
                    if (strFieldTag == "SC")
                        cmbMatchCode.Properties.Items.Add("");
                    foreach (DataRow row in dsMatchCodeValue.Tables[0].Rows)
                    {
                        ADMatchCodesInfo objADMatchCodesInfo = (ADMatchCodesInfo)objADMatchCodesController.GetObjectFromDataRow(row);
                        cmbMatchCode.Properties.Items.Add(objADMatchCodesInfo.ADMatchCodeValue);
                    }
                    if (cmbMatchCode.Properties.Items.Count > 0)
                        cmbMatchCode.SelectedIndex = 0;
                }
                else
                {
                    cmbMatchCode.Properties.Buttons.Clear();
                }
            }
            dsMatchCodeValue.Dispose();
        }

        private void InitComboBoxFromQueryString(String strQuery, ComboBox cmb)
        {
           
            DataSet ds = THSDbUtil.ExecuteQuery(strQuery);
            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    cmb.Items.Add(row[0].ToString());
                }
                if (cmb.Items.Count > 0)
                    cmb.SelectedIndex = 0;
            }
            ds.Dispose();
        }

        private void InitComboBoxFromADConfigValues
            (STFieldsInfo objSTFieldsInfo, ComboBox cmb)
        {
            String strConfigValueTable = objSTFieldsInfo.STFieldDataMember.Substring(2, objSTFieldsInfo.STFieldDataMember.Length - 7);
            cmb.DataSource = ADConfigValueUtility.glbdsConfigValues.Tables[strConfigValueTable];
            cmb.ValueMember = "Value";
            cmb.DisplayMember = "Text";
        }

        private void InitComboBoxFromADConfigValues
            (STFieldsInfo objSTFieldsInfo, DevExpress.XtraEditors.ComboBoxEdit cmb)
        {
            if (objSTFieldsInfo.STFieldTag.ToString() == "SC")
                cmb.Properties.Items.Add("");
            String strConfigValueGroup = String.Empty;
            if (objSTFieldsInfo.STFieldDataMember.Contains("Combo"))
                strConfigValueGroup = objSTFieldsInfo.STFieldDataMember.Substring(2, objSTFieldsInfo.STFieldDataMember.Length - 7);
            else
                strConfigValueGroup = objSTFieldsInfo.STFieldDataMember.Substring(2, objSTFieldsInfo.STFieldDataMember.Length - 2);
            if (ADConfigValueUtility.glbdsConfigValues.Tables[strConfigValueGroup] != null)
            {
                foreach (DataRow row in ADConfigValueUtility.glbdsConfigValues.Tables[strConfigValueGroup].Rows)
                {
                    cmb.Properties.Items.Add(row["Text"].ToString());
                }
            }
            if (cmb.Properties.Items.Count > 0)
               cmb.SelectedIndex = 0;
            else
                cmb.Text = String.Empty;
        }
        #endregion        

        #region Initialize DateEdit function
        public DevExpress.XtraEditors.DateEdit InitializeDateEdit(STFieldsInfo Field, int iLanguageID)
        {
            try
            {
                DevExpress.XtraEditors.DateEdit dte = new DevExpress.XtraEditors.DateEdit();
                dte.Name = Field.STFieldName;
                dte.BackColor = Color.FromArgb(Field.STFieldBackColor);
                dte.ForeColor = Color.FromArgb(Field.STFieldForeColor);
                dte.Font = new Font(Field.STFieldFontName, (float)Field.STFieldFontSize, (FontStyle)Enum.Parse(typeof(FontStyle), Field.STFieldFontStyle));
                dte.Location = new Point(Field.STFieldLocationX, Field.STFieldLocationY);
                dte.Size = new Size(Field.STFieldSizeWidth, Field.STFieldSizeHeight);
                dte.Enabled = Field.STFieldEnabled;
                dte.TabIndex = Field.STFieldTabIndex;
                dte.Tag = Field.STFieldTag;
                dte.Properties.Mask.EditMask = Field.STFieldEditMask;
                dte.Properties.DisplayFormat.FormatString = Field.STFieldEditMask;

                
                if (Field.STFieldName.Contains("SearchFrom") || Field.STFieldName.Contains("SearchTo"))
                {
                    if (Field.STFieldTag == THSERPScreen.SearchControl)
                    {
                        if (Field.STFieldName.Contains("SearchFrom"))
                            dte.EditValue = THSUtil.GetYearBeginDate();
                        else if (Field.STFieldName.Contains("SearchTo"))
                            dte.EditValue = THSUtil.GetYearEndDate();
                    }
                }

                if (!String.IsNullOrEmpty(Field.STFieldDataSource) && !String.IsNullOrEmpty(Field.STFieldDataMember))
                    BindingDataControl(dte);

                dte.KeyUp += new KeyEventHandler(((BaseModuleERP)Module).Control_KeyUp);
                InitializeControlEvent(Field, dte);
                return dte;
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        #region Initialize TimeEdit Function
        public DevExpress.XtraEditors.TimeEdit InitializeTimeEdit(STFieldsInfo Field, int iLanguageID)
        {
            try
            {
                DevExpress.XtraEditors.TimeEdit ted = new DevExpress.XtraEditors.TimeEdit();
                ted.Name = Field.STFieldName;
                ted.BackColor = Color.FromArgb(Field.STFieldBackColor);
                ted.ForeColor = Color.FromArgb(Field.STFieldForeColor);
                ted.Font = new Font(Field.STFieldFontName, (float)Field.STFieldFontSize, (FontStyle)Enum.Parse(typeof(FontStyle), Field.STFieldFontStyle));
                ted.Location = new Point(Field.STFieldLocationX, Field.STFieldLocationY);
                ted.Size = new Size(Field.STFieldSizeWidth, Field.STFieldSizeHeight);
                ted.Enabled = Field.STFieldEnabled;
                ted.TabIndex = Field.STFieldTabIndex;
                ted.Tag = Field.STFieldTag;
                //dte.EnterMoveNextControl = true;
                //dte.Format = (DateTimePickerFormat)Enum.Parse(typeof(DateTimePickerFormat), Field.STFieldDateTimeFormat);
                if (!String.IsNullOrEmpty(Field.STFieldDataSource) && !String.IsNullOrEmpty(Field.STFieldDataMember))
                    BindingDataControl(ted);                
                ted.KeyUp += new KeyEventHandler(((BaseModuleERP)Module).Control_KeyUp);
                InitializeControlEvent(Field, ted);
                return ted;
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        #region Initialize PictureEdit functions
        public DevExpress.XtraEditors.PictureEdit InitializePictureEdit(STFieldsInfo Field,int iLanguageID)
        {
            try
            {
                DevExpress.XtraEditors.PictureEdit pictureEdit = new DevExpress.XtraEditors.PictureEdit();
                pictureEdit.Name = Field.STFieldName;
                pictureEdit.Location = new Point(Field.STFieldLocationX, Field.STFieldLocationY);
                pictureEdit.Size = new Size(Field.STFieldSizeWidth, Field.STFieldSizeHeight);
                pictureEdit.Enabled = Field.STFieldEnabled;
                pictureEdit.TabIndex = Field.STFieldTabIndex;
                pictureEdit.Tag = Field.STFieldTag;
                if (!String.IsNullOrEmpty(Field.STFieldDataSource) && !String.IsNullOrEmpty(Field.STFieldDataMember))
                    BindingDataControl(pictureEdit);                
                pictureEdit.KeyUp += new KeyEventHandler(((BaseModuleERP)Module).Control_KeyUp);
                InitializeControlEvent(Field, pictureEdit);

                return pictureEdit;
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion
      
        #region Initialize Line functions
        public GroupBox InitializeLine(STFieldsInfo Field,int iLanguageID)
        {
            GroupBox line = new GroupBox();
            line.Name = Field.STFieldName;
            line.BackColor = Color.FromArgb(Field.STFieldBackColor);
            line.ForeColor = Color.FromArgb(Field.STFieldForeColor);
            line.Font = new Font(Field.STFieldFontName, (float)Field.STFieldFontSize, (FontStyle)Enum.Parse(typeof(FontStyle), Field.STFieldFontStyle));
            line.Location = new Point(Field.STFieldLocationX, Field.STFieldLocationY);
            line.Size = new Size(Field.STFieldSizeWidth, Field.STFieldSizeHeight);
            line.Enabled = Field.STFieldEnabled;
            line.TabIndex = Field.STFieldTabIndex;
            return line;
        }
        #endregion

        #region Initialize GroupControl functions
        public DevExpress.XtraEditors.GroupControl InitializeGroupControl(STFieldsInfo Field, int iLanguageID)
        {
            DevExpress.XtraEditors.GroupControl grc = new DevExpress.XtraEditors.GroupControl();
            grc.Name = Field.STFieldName;            
            grc.Font = new Font(Field.STFieldFontName, (float)Field.STFieldFontSize, (FontStyle)Enum.Parse(typeof(FontStyle), Field.STFieldFontStyle));
            grc.Location = new Point(Field.STFieldLocationX, Field.STFieldLocationY);
            grc.Size = new Size(Field.STFieldSizeWidth, Field.STFieldSizeHeight);            
            grc.Enabled = Field.STFieldEnabled;
            grc.TabIndex = Field.STFieldTabIndex;
            grc.Text = Field.STFieldText;
            grc.Appearance.BackColor = System.Drawing.SystemColors.Control;
            grc.Appearance.Options.UseBackColor = true;
            grc.ShowCaption = true;
            grc.MouseUp+=new MouseEventHandler(Screen_MouseUp);
            InitializeControlEvent(Field, grc);
            return grc;
        }
        #endregion

        #region Initialize PivotGridControl function
        /// <summary>
        /// Initialize PivotGridControl
        /// </summary>
        /// 
        public DevExpress.XtraPivotGrid.PivotGridControl InitializePivotGridControl(STFieldsInfo Field, int iLanguageID)
        {
            DevExpress.XtraPivotGrid.PivotGridControl pivotGrid = new DevExpress.XtraPivotGrid.PivotGridControl();
            pivotGrid.Name = Field.STFieldName;
            pivotGrid.BackColor = Color.FromArgb(Field.STFieldBackColor);
            pivotGrid.ForeColor = Color.FromArgb(Field.STFieldForeColor);
            pivotGrid.Font = new Font(Field.STFieldFontName, (float)Field.STFieldFontSize, (FontStyle)Enum.Parse(typeof(FontStyle), Field.STFieldFontStyle));
            pivotGrid.Location = new Point(Field.STFieldLocationX, Field.STFieldLocationY);
            pivotGrid.Size = new Size(Field.STFieldSizeWidth, Field.STFieldSizeHeight);
            pivotGrid.Tag = Field.STFieldTag;
            pivotGrid.TabIndex = Field.STFieldTabIndex;
            pivotGrid.Enabled = Field.STFieldEnabled;
            if (!String.IsNullOrEmpty(Field.STFieldDock))
                pivotGrid.Dock = (DockStyle)Enum.Parse(typeof(DockStyle), Field.STFieldDock);
            InitializeControlEvent(Field, pivotGrid);
            return pivotGrid;
        }
        #endregion

        #region Initialize ChartControl function
        /// <summary>
        /// Initialize ChartControl
        /// </summary>
        /// 
        public DevExpress.XtraCharts.ChartControl InitializeChartControl(STFieldsInfo Field, int iLanguageID)
        {
            DevExpress.XtraCharts.ChartControl chartControl = new DevExpress.XtraCharts.ChartControl();
            chartControl.Name = Field.STFieldName;
            chartControl.BackColor = Color.FromArgb(Field.STFieldBackColor);
            chartControl.ForeColor = Color.FromArgb(Field.STFieldForeColor);
            chartControl.Font = new Font(Field.STFieldFontName, (float)Field.STFieldFontSize, (FontStyle)Enum.Parse(typeof(FontStyle), Field.STFieldFontStyle));
            chartControl.Location = new Point(Field.STFieldLocationX, Field.STFieldLocationY);
            chartControl.Size = new Size(Field.STFieldSizeWidth, Field.STFieldSizeHeight);
            chartControl.Tag = Field.STFieldTag;
            chartControl.TabIndex = Field.STFieldTabIndex;
            chartControl.Enabled = Field.STFieldEnabled;
            if (!String.IsNullOrEmpty(Field.STFieldDock))
                chartControl.Dock = (DockStyle)Enum.Parse(typeof(DockStyle), Field.STFieldDock);
            InitializeControlEvent(Field, chartControl);
            return chartControl;
        }
        #endregion

        #region Initialize TabControl function
        /// <summary>
        /// Initialize TabControl
        /// </summary>
        /// 
        public DevExpress.XtraTab.XtraTabControl InitializeTabControl(STFieldsInfo Field, int iLanguageID)
        {
            DevExpress.XtraTab.XtraTabControl tabControl = new DevExpress.XtraTab.XtraTabControl();
            tabControl.Name = Field.STFieldName;
            tabControl.BackColor = Color.FromArgb(Field.STFieldBackColor);
            tabControl.ForeColor = Color.FromArgb(Field.STFieldForeColor);
            tabControl.Font = new Font(Field.STFieldFontName, (float)Field.STFieldFontSize, (FontStyle)Enum.Parse(typeof(FontStyle), Field.STFieldFontStyle));
            tabControl.Location = new Point(Field.STFieldLocationX, Field.STFieldLocationY);
            tabControl.Size = new Size(Field.STFieldSizeWidth, Field.STFieldSizeHeight);
            tabControl.Tag = Field.STFieldTag;
            tabControl.TabIndex = Field.STFieldTabIndex;
            tabControl.Enabled = Field.STFieldEnabled;
            if (!String.IsNullOrEmpty(Field.STFieldDock))
                tabControl.Dock = (DockStyle)Enum.Parse(typeof(DockStyle), Field.STFieldDock);
            InitializeControlEvent(Field, tabControl);
            return tabControl;
        }
        #endregion

        #region Screen Event Handlers
        public void Screen_Activated(object sender, EventArgs e)
        {
            
            base.Activate();
            this.SuspendLayout();
            this.Module.ActiveScreen = (THSScreen)sender;
            this.ResumeLayout(true);
            //Show SearchOptionPanel and SearchResults_HieuNH_03/04/2010
            ShowSearchOptionAndSearchResultsPanel();
            //Search if is exists grid SearchResults_HieuNH_03/04/2010
            SearchDefaultModule();
            
        }

        public void ShowSearchResultsPanel(THSERPScreen scr)
        {
            if (scr.ScreenInfo != null)
            {
                if (scr.ScreenInfo.STScreenShowInfoPanel)
                {
                    ((BaseModuleERP)scr.Module).ParentScreen.dockSearchResultsPanel.Show();
                    ((BaseModuleERP)scr.Module).ParentScreen.fld_barckeSearchResults.Checked = true;
                    scr.Focus();
                }
                else
                {
                    ((BaseModuleERP)scr.Module).ParentScreen.dockSearchResultsPanel.Hide();
                    ((BaseModuleERP)scr.Module).ParentScreen.fld_barckeSearchResults.Checked = false; 
                }
            }
            else
            {
                ((BaseModuleERP)scr.Module).ParentScreen.dockSearchResultsPanel.Hide();
                ((BaseModuleERP)scr.Module).ParentScreen.fld_barckeSearchResults.Checked = false;
            }
        }
        public void ShowSearchOptionAndSearchResultsPanel(THSERPScreen scr)
        {
            //if Screen showInforPanel =true show informtion panel_Hieunh_30/03/2010
            if (IsExistsGridSearchResultsInDockSearchResults())
                ShowSearchResultsPanel(scr);
            else
                ((BaseModuleERP)Module).ParentScreen.dockSearchResultsPanel.Hide();
            //Remove panel search option on ParentScreen HieuNH_22/05/2010
            //if (((BaseModuleERP)Module).ParentScreen.fld_pnlSearchOption.Controls.Count > 0)
            //{
            //    ((BaseModuleERP)Module).ParentScreen.fld_pnlSearchOption.BackColor = Color.FromArgb(this.BackColor.ToArgb());
            //    ((BaseModuleERP)Module).ParentScreen.fld_pnlSearchOption.ForeColor = Color.FromArgb(this.ForeColor.ToArgb());
            //    ((BaseModuleERP)Module).ParentScreen.fld_pnlSearchOption.Font = new Font(this.Font.Name, (float)(this.Font.Size), (FontStyle)Enum.Parse(typeof(FontStyle), this.Font.Style.ToString()));
            //    ((BaseModuleERP)Module).ParentScreen.fld_pnlSearchOption.Visible = true;
            //    ((BaseModuleERP)Module).ParentScreen.fld_barckeSearchOption.Checked = true;
            //}
            //else
            //{
            //    ((BaseModuleERP)Module).ParentScreen.fld_pnlSearchOption.Visible = false;
            //    ((BaseModuleERP)Module).ParentScreen.fld_barckeSearchOption.Checked = false;
            //}
        }

        /// <summary>
        /// Show search results and Search option Panel by following active screen
        /// </summary>
        /// <remarks>HieuNH_02/04/2010</remarks>
        /// 
        public void ShowSearchOptionAndSearchResultsPanel()
        {
            ShowSearchOptionAndSearchResultsPanel(this);
        }

        private void Screen_Closing(object sender, FormClosingEventArgs e)
        {
            STScreensController objSTScreensController = new STScreensController();
            THSERPScreen scr = (THSERPScreen)sender;                       
            
            if (scr.ScreenInfo != null)
            {
                ScreenInfo.STScreenLocationX = this.Location.X;
                ScreenInfo.STScreenLocationY = this.Location.Y;
                ScreenInfo.STScreenSizeHeight = this.Size.Height;
                ScreenInfo.STScreenSizeWidth = this.Size.Width;
                objSTScreensController.UpdateObject(ScreenInfo);
            }
            
        }

        private void Screen_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                (Module as BaseModuleERP).ParentScreen.popupMenuToolbar.ShowPopup(Control.MousePosition);
            }
        }     

        public void Control_Enter(object sender, EventArgs e)
        {
            Control ctrl = (Control)sender;
            ctrl.BackColor = Color.Yellow;
            if (ctrl is DevExpress.XtraEditors.TextEdit)
            {
                (ctrl as DevExpress.XtraEditors.TextEdit).SelectAll();
            }            
        }        

        public void Control_Leave(object sender, EventArgs e)
        {
            try
            {                
                
            }
            catch (Exception)
            {
                return;
            }
        }
        #endregion                       

        #region Init Context Menu Item

        private void ContextMenuItemNew_Click(object sender, EventArgs e)
        {
            (Module as BaseModuleERP).ActionNew();
        }

        private void ContextMenuItemEdit_Click(object sender, EventArgs e)
        {
            (Module as BaseModuleERP).ActionEdit();
        }

        private void ContextMenuItemDelete_Click(object sender, EventArgs e)
        {
            (Module as BaseModuleERP).ActionDelete();
        }

        private void ContextMenuItemCancel_Click(object sender, EventArgs e)
        {
            (Module as BaseModuleERP).ActionCancel();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <THSParam name="SearchResultsControlName" type="String"></THSParam>
        private void ContextMenuItemSave_Click(object sender, EventArgs e)
        {
            MethodInfo method = this.GetType().GetMethod("ContextMenuItemSave_Click", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new Type[2] { typeof(object), typeof(EventArgs) }, null);
            String strSearchResultsControlName = (Module as BaseModuleERP).GetModuleFunctionParameterValue(method.ToString(), method.DeclaringType.ToString(), "SearchResultsControlName");
            (Module as BaseModuleERP).ActionSave();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <THSParam name="SearchResultsControlName" type="String"></THSParam>
        private void ContextMenuItemPrevious_Click(object sender, EventArgs e)
        {
            MethodInfo method = this.GetType().GetMethod("ContextMenuItemPrevious_Click", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new Type[2] { typeof(object), typeof(EventArgs) }, null);
            String strSearchResultsControlName = (Module as BaseModuleERP).GetModuleFunctionParameterValue(method.ToString(), method.DeclaringType.ToString(), "SearchResultsControlName");
            (Module as BaseModuleERP).ActionGoPrevious();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <THSParam name="SearchResultsControlName" type="String"></THSParam>
        private void ContextMenuItemNext_Click(object sender, EventArgs e)
        {
            MethodInfo method = this.GetType().GetMethod("ContextMenuItemNext_Click", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new Type[2] { typeof(object), typeof(EventArgs) }, null);
            String strSearchResultsControlName = (Module as BaseModuleERP).GetModuleFunctionParameterValue(method.ToString(), method.DeclaringType.ToString(), "SearchResultsControlName");
            (Module as BaseModuleERP).ActionGoNext();
        }


        private void RegisterContextMenuItemsEvent()
        {
            fld_mnuNew.Click += new EventHandler(ContextMenuItemNew_Click);
            fld_mnuEdit.Click += new EventHandler(ContextMenuItemEdit_Click);
            fld_mnuDelete.Click += new EventHandler(ContextMenuItemDelete_Click);
            fld_mnuCancel.Click += new EventHandler(ContextMenuItemCancel_Click);
            fld_mnuSave.Click += new EventHandler(ContextMenuItemSave_Click);
            fld_mnuPrevious.Click += new EventHandler(ContextMenuItemPrevious_Click);
            fld_mnuNext.Click += new EventHandler(ContextMenuItemNext_Click);
        }
        
        #endregion

        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(THSERPScreen));
            this.SuspendLayout();
            // 
            // THSERPScreen
            // 
            this.Appearance.BackColor = System.Drawing.Color.Transparent;
            this.Appearance.Options.UseBackColor = true;
            this.ClientSize = new System.Drawing.Size(292, 292);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Office2003;
            this.LookAndFeel.UseDefaultLookAndFeel = false;
            this.Name = "THSERPScreen";
            this.ResumeLayout(false);

        }

              
        private void THSERPScreen_KeyUp(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.NumLock || e.KeyCode == Keys.CapsLock || e.KeyCode == Keys.Scroll)
            {

                BaseModuleERP temp = (BaseModuleERP)(this.Module);
                temp.ParentScreen.CheckKeyBoard(e);
            }
        }

        private void THSERPScreen_Activated(object sender, EventArgs e)
        {
            BaseModuleERP temp = (BaseModuleERP)(this.Module);
            temp.ParentScreen.CheckKeyBoard(null);
        }
        //-->

        /// <summary>
        /// Add all controls of module screens to various sections of parent screen
        /// basing on control's tag
        /// </summary>
        ///<remarks>_HieuNH_09/05/2010</remarks>
        public void AddControlsToParentScreen()
        {
            //If screen is data main one, add tab page to screen container
            if (IsDataMainScreen())
            {
                DevExpress.XtraTab.XtraTabPage tpScreen = new DevExpress.XtraTab.XtraTabPage();
                tpScreen.Text = this.Text;
                tpScreen.Name = "fld_tbPage" + this.ScreenNumber;
                tpScreen.MaximumSize = ((BaseModuleERP)Module).ParentScreen.ScreenContainer.Size;
                ((BaseModuleERP)Module).ParentScreen.ScreenContainer.TabPages.Add(tpScreen);
            }

            ModuleParentScreen parentScreen = ((BaseModuleERP)Module).ParentScreen;
            for (int i = 0; i < this.Controls.Count; i++)
            {
                Control ctrl = this.Controls[i];

                bool flag = false;
                if (ctrl.Tag != null)
                {
                    switch (ctrl.Tag.ToString())
                    {
                        case THSERPScreen.SearchResultControl:
                            Size controlSize = parentScreen.SearchResultsContainer.Size;
                            ctrl.Size = controlSize;
                            parentScreen.SearchResultsContainer.Controls.Add(ctrl);
                            parentScreen.SearchResultsContainer.Controls[ctrl.Name].Dock = DockStyle.Fill;
                            i--;
                            flag = true;
                            break;
                        case THSERPScreen.SearchInfo:
                        case THSERPScreen.SearchControl:
                            if (IsSearchMainScreen())
                            {
                               ((BaseModuleERP)Module).SearchScreen.CriteriaSection.Controls.Add(ctrl);
                                i--;
                                flag = true;
                            }
                            break;
                    }
                }
                if (flag == false)
                {
                    if (parentScreen.ScreenContainer.TabPages.Count > 0)
                    {
                        parentScreen.ScreenContainer.TabPages[parentScreen.ScreenContainer.TabPages.Count - 1].Controls.Add(ctrl);
                        i--;
                    }
                }
            }
        }
        //public void AddControlsToParentScreen()
        //{
        //    //If screen is data main one, add tab page to screen container
        //    if (IsDataMainScreen())
        //    {
        //        DevExpress.XtraTab.XtraTabPage tpScreen = new DevExpress.XtraTab.XtraTabPage();
        //        tpScreen.Text = this.Text;
        //        tpScreen.Name = "fld_tbPage" + this.ScreenNumber;
        //        tpScreen.MaximumSize = ((BaseModuleERP)Module).ParentScreen.ScreenContainer.Size;
        //        ((BaseModuleERP)Module).ParentScreen.ScreenContainer.TabPages.Add(tpScreen);
        //    }

        //    ModuleParentScreen parentScreen = ((BaseModuleERP)Module).ParentScreen;
        //    for (int i = 0; i < this.Controls.Count; i++)
        //    {
        //        Control ctrl = this.Controls[i];

        //        bool flag = false;
        //        if (ctrl.Tag != null)
        //        {
        //            switch (ctrl.Tag.ToString())
        //            {
        //                case THSERPScreen.SearchResultControl:
        //                    Size controlSize = parentScreen.dockSearchResultsPanel.Size;
        //                    ctrl.Size = controlSize;
        //                    parentScreen.dockPanelSearchResults_Container.Controls.Add(ctrl);
        //                    parentScreen.dockPanelSearchResults_Container.Controls[ctrl.Name].Dock = DockStyle.Fill;
        //                    i--;
        //                    flag = true;
        //                    break;
        //                case THSERPScreen.SearchInfo:
        //                case THSERPScreen.SearchControl:
        //                    if (IsSearchMainScreen())
        //                    {
        //                        parentScreen.fld_pnlSearchOption.Controls.Add(ctrl);
        //                        i--;
        //                        flag = true;
        //                    }
        //                    break;
        //            }
        //        }
        //        if (flag == false)
        //        {
        //            if (parentScreen.ScreenContainer.TabPages.Count > 0)
        //            {
        //                parentScreen.ScreenContainer.TabPages[parentScreen.ScreenContainer.TabPages.Count - 1].Controls.Add(ctrl);
        //                i--;
        //            }
        //        }
        //    }
        //}
        
        #region Generate Search Query
        protected virtual String GenerateSearchQuery(String strTableName)
        {
            StringBuilder strSearchQueryBuilder = new StringBuilder();
            strSearchQueryBuilder.Append(GenerateSearchQueryHeader(strTableName));
            if (this.Tag.ToString().Equals("SS"))
            {
                strSearchQueryBuilder.Append("WHERE" + THSUtil.NewLine);
                strSearchQueryBuilder.Append(GenerateConditionsForSearch(strTableName));
            }

            strSearchQueryBuilder.Append(THSUtil.NewLine);

            return strSearchQueryBuilder.ToString();
        }

        protected virtual String GenerateSearchQueryHeader(String strTableName)
        {
            return ((BaseModuleERP)Module).GenerateSearchQueryHeader(strTableName);
        }

        protected virtual String GenerateConditionsForSearch(String strTableName, Control.ControlCollection ctrls)
        {
           
            StringBuilder strConditionBuilder = new StringBuilder();

            foreach (Control ctrl in ctrls)
            {
                if (ctrl.Tag != null)
                {
                    if (ctrl.Tag.ToString().Equals("SC"))
                    {
                        if (ctrl.GetType() == typeof(THSGridControl) || ctrl.GetType().BaseType == typeof(THSGridControl))
                            continue;
                        String strColumnName = (ctrl as DevExpress.XtraEditors.BaseEdit).Properties.AccessibleName;
                        if (String.IsNullOrEmpty(strColumnName))
                            strColumnName = THSDbUtil.GetPropertyStringValue(ctrl, THSERPScreen.cstDataMemberPropertyName);
                        strConditionBuilder.Append(((BaseModuleERP)Module).GenerateConditionsForSearch(ctrl, strTableName, strColumnName));
                    }
                }
                if (ctrl.Controls.Count > 0)
                    strConditionBuilder.Append(GenerateConditionsForSearch(strTableName, ctrl.Controls));
            }
            //strConditionBuilder.Append(THSUtil.Tab + String.Format("([AAStatus]='Alive')") + THSUtil.NewLine);
            return strConditionBuilder.ToString();
        }

        protected virtual String GenerateConditionsForSearch(String strTableName)
        {
            StringBuilder strConditionBuilder = new StringBuilder();
            strConditionBuilder.Append(GenerateConditionsForSearch(strTableName, Controls));
            strConditionBuilder.Append(THSUtil.Tab + String.Format("([AAStatus]='Alive')") + THSUtil.NewLine);
            return strConditionBuilder.ToString();
        }

        /// <summary>
        /// after active screen, call search funtion
        /// </summary>
        public void SearchDefaultModule()
        {
            if (IsExistsGridSearchResultsInDockSearchResults())
            {
                if (((BaseModuleERP)Module).Toolbar.CurrentObjectID <= 0)
                    ((BaseModuleERP)Module).Search();
            }
        }

        private bool IsExistsGridSearchResultsInDockSearchResults()
        {
            String strMainObjectTableName = THSUtil.GetTableNameFromBusinessObject(((BaseModuleERP)Module).CurrentModuleEntity.MainObject);
            String strSearchResultsControlName = String.Format("fld_dgc{0}", strMainObjectTableName.Substring(0, strMainObjectTableName.Length - 1));
                           // parentScreen.dockPanelSearchResults_Container.Controls.Add(ctrl);
            DevExpress.XtraGrid.GridControl gridControl = (DevExpress.XtraGrid.GridControl)((BaseModuleERP)Module).ParentScreen.SearchResultsContainer.Controls[strSearchResultsControlName];
            if (gridControl != null)
                return true;
            return false;
        }

        /// <summary>
        /// Display text basing on business object for all labels of the screen
        /// </summary>
        /// 
        
        public virtual void DisplayLabelText(BusinessObject obj, Control.ControlCollection controls)
        {
            foreach (Control ctrl in controls)
            {
                ((BaseModuleERP)Module).DisplayLabelText(obj, ctrl);
                if (ctrl.Controls.Count > 0)
                    DisplayLabelText(obj, ctrl.Controls);
            }
        }
        #endregion
    }
}